package org.x.api.system.filter;

import cn.dev33.satoken.same.SaSameUtil;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.*;
import org.x.common.base.constants.UserContext;
import org.x.common.base.util.UserContextHolder;

@Activate(group = CommonConstants.CONSUMER,order = Integer.MAX_VALUE)
public class TenantConsumerFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        String token = SaSameUtil.getToken();
        if(StringUtils.isNotBlank(token)){
            // 追加 Same-Token 参数
            invocation.setAttachment(SaSameUtil.SAME_TOKEN,token);
        }

        String tenantId = UserContextHolder.getTenantId();
        if (StringUtils.isNotBlank(tenantId)) {
            RpcContext.getClientAttachment().setAttachment(UserContext.TENANT_ID, tenantId);
        }
        try{
            // 开始调用
            return invoker.invoke(invocation);
        }catch (RpcException e){
            throw new RpcException(
                    "服务调用失败: " + e.getMessage(),
                    e
            );
        }
    }
}